#include "../../include/threadpool/threadpool.h"
#include "../../include/log/log.h"
#include <thread>
#include <assert.h>
#include <iostream>

void ThreadPool::worker(ThreadPool* threadPool)
{
    assert(threadPool);
    threadPool->runAllTime();
}

ThreadPool::ThreadPool(int threadNumber)
{
    assert(threadNumber > 0);
    sem_init(&sem, 0, 0);
    for(int i = 0; i < threadNumber; ++i)
    {
        std::thread t(worker, this);
        t.detach();
    }
}

bool ThreadPool::push(StrategyService* strategyService, int state)
{
    strategyService->state = state;
    std::lock_guard<std::mutex> lock(m_mutex);
    if(workList.size() >= maxWorkTasks)
    {
        ErrorLog("workList push failed");
        return false;
    }
    readTimes++;
    workList.push_back(strategyService);
    sem_post(&sem);
    return true;
}

void ThreadPool::runAllTime()
{
    while(1)
    {
        sem_wait(&sem);
        InfoLog("start run thread");
        InfoLog("thread id is:[%d]", std::this_thread::get_id());
        StrategyService* strategyService = new StrategyService;
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            if (workList.size() <= 0) {
                ErrorLog("worklist siez is 0, work failed");
                continue;
            }
            strategyService = workList.front();
            workList.pop_front();
        }
        if(strategyService->state == 0)
        {
            strategyService->readJson();
        }
        else
        {
            strategyService->writeJson();
        }
    }
}

